<?php
require_once("inc.member.php");

$this_title="$vars[member_title] &raquo; ".__("Convert Bonus Chip to e-Chip");
$page_title=__("Convert Bonus Chip to e-Chip");
$content_title=__("Convert Bonus Chip to e-Chip");

$item_per_page=$vars["user_item_per_page"];

require_once("inc.wallet_select.php");

if($r_user['ewallet']<=0){
 $errmsg=__("Make sure your e-wallet have balance")."<br />\n";
}
if($errmsg){
 print format_member_page($inc_wallet_select."<h2>$page_title</h2>".format_err($errmsg), $this_title, $content_title, $inc_jvscript);
 exit();
}

$td_width=180;

/*##### FORM POST #####*/
if($_POST["__req"]){

 if(!$errmsg){
	//check password
  	if(!strlen($post_s["password"])){
   		$errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Password")))."<br />\n";
  	}else{
   		$enc_pass=explode(":", $r_user["ewallet_enc_password"]);
   		if(md5($post_s["password"].$enc_pass[1]) != $enc_pass[0]){
    		$errmsg.=__("You have entered an invalid Password.")."<br />\n";
   		}
  	}
  
  	//check min withdraw amount
  	if($post_s["_amount"]<0){
   		$errmsg.=__("Convert amount must more than 0.")."<br />\n";
  	//check cash balance
  	}elseif(!is_numeric($post_s["_amount"])){
  		$errmsg.=__("Convert amount must be numeric.")."<br />\n";
  	}elseif($post_s["_amount"]>$r_user["ewallet"]){
   		$errmsg.=replace_tag(__("You do not have sufficient <%title%>."), array("<%title%>"=>__($vars["ewallet_title"])))."<br />\n".replace_tag(__("<%title%> requested: <%x%>"), array("<%title%>"=>__($vars['ewallet_title']), "<%x%>"=>number_format($post_s['_amount'], 2)))."<br />\n".replace_tag(__("<%title%> available: <%x%>"), array("<%title%>"=>__($vars['ewallet_title']), "<%x%>"=>number_format($r_user['ewallet'], 2)))."<br />\n";
  	}
 }
 
 if(!$errmsg){
  	if($post_s["__confirm"]){
   		$datetime=ndate($vars["system_date_format"]);
	   	
	    //create e-wallet record	    	
	    if(!mysql_query($ewr_sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$post_d[_amount]', '".AddSlashes("Convert $vars[currency]".number_format($post_d['_amount'], 2)." into register point")."', '$datetime')")){
	    	$critical_error.="Error creating the member $vars[ewallet_title] record when member ID #$uid request convert e-wallet to register point. Please manually execute the SQL below to record the transaction:<br />\n<br />\n$sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
	    }else{
			$new_eid = mysql_insert_id();
			$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
			if(!$last_bal){
				$last_bal = 0;
			}
			$last_bal -= $post_s['_amount'];
			@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
		}
	    //create withdrawal record
	    $sql="insert into $db->member_eswallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$post_d[_amount]', '".AddSlashes("Convert $vars[currency]".number_format($post_d['_amount'], 2)." into register point")."', '$datetime')";
	    if(!mysql_query($sql)){
	    	$errmsg.=__("We have some error processing your convert e-wallet to register point request.")." ".replace_tag(__("Your <%title%> account has been deducted <%x%>."), array("<%title%>"=>__($vars["ewallet_title"]), "<%x%>"=>number_format($post_s["_amount"], 2)))." ".__("Please contact us.")."<br />\n".($vars["debug"]? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
	    	$critical_error.="Error creating the member register point record when member ID #$uid request convert e-wallet to register point and this member's $vars[ewallet_title] account has been deducted ".number_format($post_s["_amount"], 2).". Please manually record this convert e-wallet by executing SQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
	    }else{
	    	$new_esid=mysql_insert_id();
	    	$last_bal = @mysql_result(mysql_query("select bal from $db->member_eswallet_record where uid='$uid' and id!=$new_esid order by id desc limit 1"), 0);
			if(!$last_bal){
				$last_bal = 0;
			}
			$last_bal += $post_s['_amount'];
			@mysql_query("update $db->member_eswallet_record set bal='$last_bal' where id='$new_esid' limit 1");
	    }
	    	
	    if(!mysql_query($sql="update $db->users set ewallet=ewallet-$post_d[_amount],eswallet=eswallet+$post_d[_amount] where id='$uid' limit 1")){
	    	$errmsg.=__("We have some error processing your convert e-wallet to register point request.")." ".__("You can try again later. If the problem persists, please contact us.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
		}else{
			$msg=__("Your have successful convert e-wallet to register point.")."<br />\n";			
		}
 	}
 }

 if($critical_error){
  	$a_sub="$vars[title] - Membership convert e-wallet to register point for member ID #$uid";
  	$a_msg="<p>Dear admin,</p>
  		<p>There was some error(s) while member ID #$uid requests for convert e-wallet to register point. The error is as follow:</p>
  	$critical_error";
  	email_admin($a_sub, $a_msg, 'e');
 }

 $errmsg=$errmsg? format_err($errmsg) : "";
 $msg=$msg? format_msg($msg) : "";
}

$form_fields=array("_amount"=>"","password"=>"");
foreach($form_fields as $field => $default){
 $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
 if(!$msg)
 	$dis[$field]=(!$posting? $default : $post_h[$field]);
}

if(!$errmsg && $post_s["__preview"]){
 $preview=true;
 foreach($dis as $field=>$value){
  $post_fields.="<input type='hidden' name='$field' value=\"$value\" />\n";
 }
}

//javascript
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 j('form[@name=convert_form]').submit(function(){
  j('input[@name=submit_btn]').attr('disabled','disabled');
 });
});

function form_back(){
 document.convert_form.__confirm.value='';
 document.convert_form.submit();
}
</script>";

$display_fields=array("_amount");
foreach($form_fields as $field=>$default){
 if(in_array($field, $display_fields)){
  $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
  $dbr=explode("#", $vars["dbr"]["member_convert"][$db_fieldname]);
  $readonly=$textarea=$password=false;
  $extra_display="";
  if($field=='_amount'){
   $extra_display="<br />\n<span>".replace_tag(__("<%title%> Available: <%currency%><%x%>"), array("<%title%>"=>__($vars["ewallet_title"]), "<%currency%>"=>$vars["currency"], "<%x%>"=>number_format($r_user["ewallet"], 2)))."</span><br />\n
   ";
  }
  if($field=='_remark'){
   $textarea=true;
  }
  if($field=='password'){
   $password=true;
  }
  $add_class="";
  $readonly_str=$readonly? "readonly='readonly' class='readonly'" : "";
  $add_class=$readonly? "readonly" : "";
  $inputbox_style2=$add_class? preg_replace('/^class=\'/', "class='$add_class ", $inputbox_style) : $inputbox_style;
  $form_inputfield[$db_fieldname]="
  <tr id='input_$db_fieldname'>
   <td width='$td_width'>".__($dbr[4]).__(":").($dbr[3]=='m'? " ".__("*") : "")."</td>
   <td>".($preview? $dis[$field] : ($textarea? "<textarea name='$field' rows='6' $inputbox_style2 $readonly_str>".$dis[$field]."</textarea>" : "
   <input type='".($password? "password" : "text")."' name='$field' $inputbox_style2 value=\"".$dis[$field]."\" $readonly_str />")."$extra_display")."</td>
  </tr>";
 }
}


//#####Preview
if($preview){
$withdrawal=
"<form name='convert_form' method='post' action='$this_file'>
<input type='hidden' name='__req' value='1' />
<input type='hidden' name='__confirm' value='1' />
$post_fields
<table class='pbt_table'>
 $form_inputfield[amount]
 <tr>
  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
   <input type='button' value=\"".__("Back")."\" class='button' onclick=\"form_back();\" /> &nbsp;&nbsp;&nbsp;
   <input type='submit' name='submit_btn' value=\"".__("Confirm")."\" class='button' />
  </td>
 </tr>
</table>
</form>";
//#####Start / Edit
}else{
	$r_user=get_user_detail_by_id($uid);
	if($r_user['country']=='TH'){
		$withdrawal=($errmsg || $msg?
		"$errmsg $msg" : "")."
		<form name='convert_form' method='post' action='$this_file'>
		<input type='hidden' name='__req' value='1' />
		<input type='hidden' name='__preview' value='1' />
		<table class='pbt_table'>
		 $form_inputfield[amount]
		 <tr>
		  <td>".__("e-Wallet Password").__(":")." ".__("*")."</td>
		  <td><input type='password' name='password' value=\"$dis[password]\" $inputbox_style /></td>
		 </tr>
		 <tr>
		  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
		   <input type='submit' name='submit_btn' value=\"".__("Preview")."\" />
		  </td>
		 </tr>
		</table>
		</form>";
	}else{
		$withdrawal=($errmsg || $msg?
		"$errmsg $msg" : "")."
		<form name='convert_form' method='post' action='$this_file'>
		<input type='hidden' name='__req' value='1' />
		<input type='hidden' name='__preview' value='1' />
		<table class='pbt_table'>
		 $form_inputfield[amount]
		 <tr>
		  <td>".__("e-Wallet Password").__(":")." ".__("*")."</td>
		  <td><input type='password' name='password' value=\"$dis[password]\" $inputbox_style /></td>
		 </tr>
		 <tr>
		  <td colspan='2'><b>".__("1 bonus chip point need 1 e-Wallet to convert. After convert you will get 2 e-Chip point")."</b></td>
		 </tr>
		 <tr>
		  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
		   <input type='submit' name='submit_btn' value=\"".__("Preview")."\" />
		  </td>
		 </tr>
		</table>
		</form>";
	}
}

$content=$inc_wallet_select."<h2>$page_title</h2>$withdrawal";

print format_member_page($content, $this_title, $content_title, $css.$jvscript.$inc_jvscript);
?>